package com.ruoyi.system.pool;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @description: shell执行器
 * @author: stone
 * @date: Created by 2022/4/16 18:39
 * @version: 1.0.0
 * @pakeage: com.ruoyi.system.pool
 */
@Slf4j
public class ShellExecutor implements Executor<String> {

    private Session session;

    public ShellExecutor(Session session) {
        this.session = session;
    }

    @Override
    public ChannelExec openChannelExec(Session session) {
        ChannelExec channelExec = null;
        try {
            channelExec = (ChannelExec) session.openChannel("exec");
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return channelExec;
    }

    @Override
    public void closeChannelExec(ChannelExec channelExec) {
        if (channelExec != null) {
            channelExec.disconnect();
        }
    }

    @Override
    public String execute(String cmd) {
        log.info("获取连接....");
        ChannelExec channelExec = openChannelExec(session);
        channelExec.setCommand(cmd);
        String result = "";
        BufferedReader bufferedReader = null;
        try {
            channelExec.setInputStream(null);
            channelExec.setErrStream(System.err);
            //InputStream in = channelExec.getInputStream();
            channelExec.connect();


            bufferedReader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));

            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                result += line + "\n";
            }
            if (result != null && !result.equals("")) {
                result = result.substring(0, result.length() - 1);
            }
            //channelExec.disconnect();
            log.info("DONE");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            channelExec.disconnect();

        }
        return result;
    }
}
